<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/14
 * Time: 10:01
 */

namespace app\api\middleware;


use app\api\model\User;
use app\Request;
use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;

class Token
{
    /**
     * 验证token 验证权限 并记录操作日志
     * @param Request $request
     * @param Closure $next
     * @return mixed|void
     */
    public function handle(Request $request, Closure $next)
    {
        $jwtToken = $request->header('token'); // 获取JWT Token
        if (!$jwtToken) die(json_encode(['code' => 401, 'msg' => '未授权的API请求！'], JSON_UNESCAPED_UNICODE));
        try {
            $jwtInfo = (array)JWT::decode($jwtToken, new Key(Config::get('jwt.key'), 'HS256')); // 使用JWT解密Token
            $request->userInfo = User::where('id', $jwtInfo['sub'])->find(); // 将解密后的JWT信息存储在请求对象中，后续控制器可以使用
        } catch (\Exception $e) {
            die(json_encode(['code' => 401, 'msg' => $e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
        return $next($request); // 继续后续请求处理
    }
}